package com.somsoft.unlockme;

import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.somsoft.unlockme.fk.C;
import com.somsoft.unlockme.fk.FangKuai;
import com.somsoft.unlockme.fk.Fk90x90;

public class UnlockMeView extends SurfaceView implements SurfaceHolder.Callback{

	private Bitmap select,reload,jump,next1,next2;
	
	UnlockMeActivity activity;
	UnlockMeDrawThread thread;			          //后台重绘线程
	
	public static List<FangKuai> fks;
	boolean isPass = false;
	int tmpX,tmpY;
	
	public UnlockMeView(UnlockMeActivity activity) {
		super(activity);
		this.activity = activity;
		getHolder().addCallback(this);	
		initBitmap();
		fks = Maps.get(C.currLevel);
		FangKuai fk = new Fk90x90(0, 0);
		tmpX = fk.getX();
		tmpY = fk.getY();
		activity.getNextInfo();
		C.moveable = true;
	}
	
	//初始化图片资源
	private void initBitmap(){
		C.background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
		C.fk90x90 = BitmapFactory.decodeResource(getResources(), R.drawable.fk90x90);
		C.fk90x180 = BitmapFactory.decodeResource(getResources(), R.drawable.fk90x180); 
		C.fk180x90 = BitmapFactory.decodeResource(getResources(), R.drawable.fk180x90); 
		C.fk180x180 = BitmapFactory.decodeResource(getResources(), R.drawable.fk180x180); 
		
		select = BitmapFactory.decodeResource(getResources(), R.drawable.select);
		reload = BitmapFactory.decodeResource(getResources(), R.drawable.reload);
		jump = BitmapFactory.decodeResource(getResources(), R.drawable.jump);
		next1 = BitmapFactory.decodeResource(getResources(), R.drawable.next1);
		next2 = BitmapFactory.decodeResource(getResources(), R.drawable.next2);
	}

	protected void doDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawColor(Color.BLACK);		//清屏
		
		Paint paint = new Paint();		
		paint.setARGB(255, 0, 0, 0);
		paint.setTextAlign(Align.CENTER); 
		paint.setColor(Color.rgb(227, 177, 117));
		
		Matrix m1 = new Matrix();
		m1.setTranslate(C.leftKongBai, C.topKongBai);
		
		Matrix m2 = new Matrix();
		m2.setScale(C.scaleBitmap, C.scaleBitmap);
		Matrix m3 = new Matrix();
		m3.setConcat(m1, m2);
		
		canvas.drawBitmap(C.background, m3, paint);
		for(FangKuai fk : fks){
			m1.setTranslate(fk.getX(),fk.getY());
			m3.setConcat(m1, m2);
			canvas.drawBitmap(fk.getPic(), m3, paint);
		}
		m1.setTranslate(tmpX,tmpY-110*C.scaleScreen);
		m3.setConcat(m1, m2);
		canvas.drawBitmap(select, m3, paint);
		
		m1.setTranslate(tmpX+135*C.scaleScreen,tmpY-110*C.scaleScreen);
		m3.setConcat(m1, m2);
		canvas.drawBitmap(reload, m3, paint);
		
		m1.setTranslate(tmpX+270*C.scaleScreen,tmpY-110*C.scaleScreen);
		m3.setConcat(m1, m2);
		/* 三种情况
		 * 1、下一关已通过，显示浅色下一关标志
		 * 2、本关过关，显示深色下一关标志
		 * 3、下一关未通过，显示“跳”
		 */
		String tmp = "";
		if(C.nextLevel!=null && "Y".equals(C.nextLevel.getIsLock())){
			canvas.drawBitmap(jump, m3, paint);
			tmp = "jump";
		}else{
			if(C.moveable){
				canvas.drawBitmap(next1, m3, paint);
				tmp = "next0";
			}else{
				canvas.drawBitmap(next2, m3, paint);
				tmp = "next";
			}
		}
		C.icons.clear();
		if(C.icons.size()==0){
			C.icons.add(new Page("select",tmpX,(int)(tmpY-110*C.scaleScreen), (int)(90*C.scaleScreen)));
			C.icons.add(new Page("reload",(int)(tmpX+135*C.scaleScreen),(int)(tmpY-110*C.scaleScreen), (int)(90*C.scaleScreen)));
			C.icons.add(new Page(tmp,(int)(tmpX+270*C.scaleScreen),(int)(tmpY-110*C.scaleScreen), (int)(90*C.scaleScreen)));
		}
		paint.setTextSize(50*C.scaleScreen);//设置字体大小
		canvas.drawText("第   "+C.currLevel+"   关", 480*C.scaleScreen/2, 80*C.scaleScreen, paint);
		
		paint.setTextAlign(Align.LEFT); 
		paint.setTextSize(22*C.scaleScreen);//设置字体大小
		canvas.drawText("最佳成绩："+C.getBest()+"步       当前移动："+C.currMoves+"步", 50*C.scaleScreen, 115*C.scaleScreen, paint);
		
		//得分情况，星形
		for(int k=0;k<3;k++){
			m1.setTranslate((195+k*30)*C.scaleScreen, 120*C.scaleScreen);
			m3.setConcat(m1, m2);
			if(k>=C.score){
				canvas.drawBitmap(C.star2, m3, paint);
			}else{
				canvas.drawBitmap(C.star1, m3, paint);
			}
		}
		
		if(C.playMovie && currFangKuai.getY()<C.height){
			//让大方块通过出口
			currFangKuai.setY(currFangKuai.getY()+(int)(90*C.scaleScreen));
		}else{
			C.playMovie = false;
		}
	}


	private int topBj = C.startY, bottomBj = C.unit * 5 + C.startY;
	private int leftBj = C.startX, rightBj = C.unit * 4 + C.startX;// 定义四边的边界
	private int tmpTopBj,tmpBottomBj,tmpLeftBj,tmpRightBj;//临时边界，碰撞后改变
	private int downX,downY;//手指按下时的坐标
	private int finalFkX,finalFkY;//最终修正的坐标
	private int currX,currY;//当前坐标
	private int juliX,juliY;//xy方向的移动距离
	private int pressJuliX,pressJuliY;//按下的点与方块坐标的距离
	private int fkX,fkY;//方块坐标
	
	private String lastDir;//手指抬起前的移动方向
	private int fkIndex = 0;                    //当前选中的方块在List中的位置
	private FangKuai currFangKuai;//当前选中的方块
	private FangKuai pzFangKuai;//碰撞的方块
	private int pzIndex = -1;//是否与其他方块碰撞,碰撞方块的index
	private boolean moveLR = true,moveTB = true;//是否允许横向移动/纵向移动
	private int downFkX,downFkY,currFkX,currFkY;//按下时方块的位置，当前方块的位置
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		/*
		 * 0、当前选中的块
		 * 1、判断移动方向
		 * 2、是否能够移动
		 * 3、移动距离
		 * 4、控制边界
		 */
		int action = event.getAction();
		
		boolean isGetFkIndex = true;//是否获取方块index，按下时获取，移动过程中不再获取，松开后，重新按下再次获取
		
		if(action == MotionEvent.ACTION_DOWN && isGetFkIndex){
			downX = (int) event.getX() ;
			downY = (int) event.getY() ;
			fkIndex = getFangkuaiIndex(downX,downY);
			if(fkIndex >=0){
				currFangKuai = fks.get(fkIndex);
				downFkX = currFangKuai.getX();
				downFkY = currFangKuai.getY();
				pressJuliX = downX - currFangKuai.getX();
				pressJuliY = downY - currFangKuai.getY();
				tmpTopBj = topBj;tmpBottomBj = bottomBj;tmpLeftBj = leftBj;tmpRightBj = rightBj;
				isGetFkIndex = false;
			}
		}else if(action == MotionEvent.ACTION_UP){
			isGetFkIndex = true;
			moveLR = true;moveTB = true;
			fkX=0;fkY=0;
			tmpTopBj = topBj;tmpBottomBj = bottomBj;tmpLeftBj = leftBj;tmpRightBj = rightBj;
			if(fkIndex>=0 && C.moveable){
				//修正移动位置
				if ("right".equals(lastDir)) {
					finalFkX = (int)Math.ceil((currFkX - downFkX)/1.0/C.unit)*C.unit + downFkX;
					currFangKuai.setX((int) finalFkX);
					if(finalFkX>downFkX){
						C.currMoves++;
					}
				} else if ("left".equals(lastDir)) {
					finalFkX = downFkX - (int)Math.ceil((downFkX - currFkX)/1.0/C.unit)*C.unit ;
					currFangKuai.setX((int) finalFkX);
					if(finalFkX<downFkX){
						C.currMoves++;
					}
				} else if ("up".equals(lastDir)) {
					finalFkY = downFkY - (int)Math.ceil((downFkY - currFkY)/1.0/C.unit)*C.unit ;
					currFangKuai.setY((int) finalFkY);
					if(finalFkY<downFkY){
						C.currMoves++;
					}
				} else if ("down".equals(lastDir)) {
					finalFkY = (int)Math.ceil((currFkY - downFkY)/1.0/C.unit)*C.unit + downFkY;					
					currFangKuai.setY((int) finalFkY);
					if(finalFkY>downFkY){
						C.currMoves++;
					}
				}
//				if(currFangKuai.isKing() && currFangKuai.getX()==C.successX && currFangKuai.getY()==C.successY){
//					isPass = true;
//					C.moveable = false;
//					C.playMovie = true;
//				}
			}
			
			for(Page p : C.icons){
				boolean b = isCollsion(p.getX(),p.getY(),p.getSize(),p.getSize(),(int) event.getX(),(int) event.getY());
				if(b){
					C.clickedBtn = p.getType();
					break;
				}
			}
		}else if(action==MotionEvent.ACTION_MOVE && fkIndex >= 0 && C.moveable){
			//fkIndex >= 0确保按下的地方是方块，而不是其他元素
			currX = (int) event.getX() ;
			currY = (int) event.getY() ;
			//判断移动了多少距离
			juliX = currX - downX;
			juliY = currY - downY;
			if (Math.abs(juliX) > Math.abs(juliY) && juliX > 0) {
				// 向右
				if(moveLR){
					lastDir = "right";
					fkX = currX - pressJuliX;
					if(tmpRightBj==rightBj){
						getPzParamLeftRight(fkX,currFangKuai,fkIndex);
					}
					if (pzIndex >= 0) {
						tmpRightBj = pzFangKuai.getX();
					}
					if ((fkX + currFangKuai.getWidth()) > tmpRightBj) {
						fkX = tmpRightBj - currFangKuai.getWidth();
					}
					moveTB = false;
				}
			} else if (Math.abs(juliX) > Math.abs(juliY) && juliX < 0) {
				// 向左
				if(moveLR){
					lastDir = "left";
					fkX = currX - pressJuliX;
					if(tmpLeftBj==leftBj){
						getPzParamLeftRight(fkX,currFangKuai,fkIndex);
					}
					if (pzIndex >= 0) {
						tmpLeftBj = pzFangKuai.getX() + pzFangKuai.getWidth();
					}
					if (fkX < tmpLeftBj) {
						fkX = tmpLeftBj;
					}
					moveTB = false;
				}
			} else if (Math.abs(juliY) > Math.abs(juliX) && juliY > 0) {
				// 向下
				if(moveTB){
					lastDir = "down";
					fkY = currY - pressJuliY;
					if(tmpBottomBj==(bottomBj)){
						getPzParamTopBottom(fkY,currFangKuai,fkIndex);
					}
					if (pzIndex >= 0) {
						tmpBottomBj = pzFangKuai.getY();
					}
					if ((fkY + currFangKuai.getHeight()) > tmpBottomBj) {
						fkY = tmpBottomBj - currFangKuai.getHeight();
					}
					moveLR = false;
				}
			} else if (Math.abs(juliY) > Math.abs(juliX) && juliY < 0) {
				// 向上
				if(moveTB){
					lastDir = "up";
					fkY = currY - pressJuliY;
					if(tmpTopBj==topBj){
						getPzParamTopBottom(fkY,currFangKuai,fkIndex);
					}
					if (pzIndex >= 0) {
						tmpTopBj = pzFangKuai.getY() + pzFangKuai.getHeight();
					}
					if (fkY < tmpTopBj) {
						fkY = tmpTopBj ;
					}
					moveLR = false;
				}
			}
			if(fkX>0){
				currFangKuai.setX(fkX);
			}
			if(fkY>0){
				currFangKuai.setY(fkY);
			}
			currFkX = currFangKuai.getX();
			currFkY = currFangKuai.getY();
		}
		return true;
	}
	
	
	private void getPzParamLeftRight(int fkX,FangKuai currFangKuai,int fkIndex){
		pzIndex = getPzIndexLeftRight(fkX,currFangKuai,fkIndex);
		if(pzIndex>=0){
			pzFangKuai = fks.get(pzIndex);
		}
	}
	
	private void getPzParamTopBottom(int fkY,FangKuai currFangKuai,int fkIndex){
		pzIndex = getPzIndexTopBottom(fkY,currFangKuai,fkIndex);
		if(pzIndex>=0){
			pzFangKuai = fks.get(pzIndex);
		}
	}
	
	/**
	 * 判断当前选取的方块的索引号
	 * @param x
	 * @param y
	 * @return
	 */
	private int getFangkuaiIndex(int x,int y){
		for(int i=0;i<fks.size();i++){
			boolean flag = isCollsion(fks.get(i).getX(),fks.get(i).getY(),fks.get(i).getWidth(),fks.get(i).getHeight(),x,y);
			if(flag){
				return i;
			}
		}
		return -1;
	}
	
	//获取碰撞的方块的index
	private int getPzIndexLeftRight(int x,FangKuai fk ,int index){
		for(int i=0;i<fks.size();i++){
			boolean flag = isCollsionWithRect(x,fk.getY(),fk.getWidth(),fk.getHeight(),fks.get(i).getX(),fks.get(i).getY(),fks.get(i).getWidth(),fks.get(i).getHeight());
			if(flag && index!=i){
				return i;
			}
		}
		return  -1;
	}
	
	//获取碰撞的方块的index
	private int getPzIndexTopBottom(int y,FangKuai fk ,int index){
		for(int i=0;i<fks.size();i++){
			boolean flag = isCollsionWithRect(fk.getX(),y,fk.getWidth(),fk.getHeight(),fks.get(i).getX(),fks.get(i).getY(),fks.get(i).getWidth(),fks.get(i).getHeight());
			if(flag && index!=i){
				return i;
			}
		}
		return  -1;
	}
		
	/**
	 * 判断矩形是否与该点碰撞
	 * @param recX
	 * @param recY
	 * @param recWidth
	 * @param recHeight
	 * @param pX
	 * @param pY
	 * @return
	 */
	public boolean isCollsion(int recX, int recY, int recWidth, int recHeight, int pX,int pY){
		if(pX >= recX && pX <= recX+recWidth && pY >= recY && pY <= recY+recHeight){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	  * 矩形碰撞的函数
	  * @param x1 第一个矩形的X坐标
	  * @param y1 第一个矩形的Y坐标
	  * @param w1 第一个矩形的宽
	  * @param h1 第一个矩形的高
	  * @param x2 第二个矩形的X坐标
	  * @param y2 第二个矩形的Y坐标
	  * @param w2 第二个矩形的宽
	  * @param h2 第二个矩形的高
	  */
	public boolean isCollsionWithRect(int x1, int y1, int w1, int h1, int x2,
			int y2, int w2, int h2) {
		// 当矩形1位于矩形2的左侧
		if (x1 >= x2 && x1 >= x2 + w2) {
			return false;
			// 当矩形1位于矩形2的右侧
		} else if (x1 <= x2 && x1 + w1 <= x2) {
			return false;
			// 当矩形1位于矩形2的上方
		} else if (y1 >= y2 && y1 >= y2 + h2) {
			return false;
		} else if (y1 <= y2 && y1 + h1 <= y2) {
			return false;
		}
		// 所有不会发生碰撞都不满足时，肯定就是碰撞了
		return true;
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		thread = new UnlockMeDrawThread(this,getHolder());
		if(!thread.isAlive()){			//启动后台绘制线程
			Log.i("", "线程启动===============");
			thread.start();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if(thread.isAlive()){				//停止后台绘制线程
			thread.flag = false;
			Log.i("", "线程结束===============");
		}	
	}
	
}



















